package router

import (
	"gopkg.in/gin-gonic/gin.v1"
	"net/http"
	"strconv"
	"github.com/dchest/uniuri"
	"os"
	"path"
	"../qiniu"
	"../domain"

)

const (
	Success  = iota + 1
	Failure
	NotExist

)

type ResData struct {
	Status int `json:"status"`
	Data   interface{} `json:"data"`
	Msg    string `json:"msg"`
}


type Size interface {
	Size() int64
}
// 获取文件信息的接口
type Stat interface {
	Stat() (os.FileInfo, error)
}
func init() {
	// Creates a gin router with default middleware:
	// logger and recovery (crash-free) middleware
	router := gin.Default()


	router.GET("/market/:id", func(c *gin.Context) {

		id := c.Param("id")
		market, ok := domain.GetMarket(id)
		data := ResData{}
		if ok {
			data.Status = Success
			data.Data = market

		} else {
			data.Status = NotExist
			data.Msg = "不存在"
		}
		c.JSON(http.StatusOK, data)

	})

	router.GET("/goods/:barcode", func(c *gin.Context) {
		barcode := c.Param("barcode")
		g, ok := domain.GetGoods(barcode)

		data := ResData{}
		if ok {
			g.PictureUrl =picture.QiniuConf.Domain + g.Picture
			data.Status = Success
			data.Data = g

		} else {
			data.Status = NotExist
			data.Msg = "不存在"
		}
		c.JSON(http.StatusOK, data)

	})

	router.PUT("/goods", func(c *gin.Context) {
		g := domain.Goods{}
		g.Id = uniuri.New()
		g.Name = c.PostForm("name")
		g.Price,_ = strconv.ParseFloat(c.PostForm("price"),64)
		g.Off,_ = strconv.ParseFloat(c.PostForm("off"),64)
		g.Category,_ = strconv.Atoi(c.PostForm("category"))
		g.Barcode = c.PostForm("barcode")
		file, header , err := c.Request.FormFile("picture")

		if err == nil {
			var fileSize int64
			if sizeInterface, ok := file.(Size); ok {
				fileSize = sizeInterface.Size()

			}
			//file.Seek(0, 0 )http://or2hj7xb7.bkt.clouddn.com/Z8280dhHZuWKo14Ook.png
			filename := header.Filename
			var filenameWithSuffix string
			filenameWithSuffix = path.Base(filename) //获取文件名带后缀
			ret,err :=picture.UpLoad(file,fileSize,g.Id+filenameWithSuffix)
			if err == nil {
				g.Picture = ret.Key
			}
		}

		_,ok :=domain.AddGoods(g)

		data := ResData{}
		if ok {
			g.PictureUrl =picture.QiniuConf.Domain + g.Picture
			data.Status = Success
			data.Data = g
		} else {
			data.Status = Failure
			data.Msg = "添加失败"
		}
		c.JSON(http.StatusOK, data)
	})

	// By default it serves on :8080 unless a
	// PORT environment variable was defined.
	router.Run()
	// router.Run(":3000") for a hard coded port
}
